package com.victor.controller.mobile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.Bybookcoupon;
import com.victor.entity.Praise;
import com.victor.service.BybookcouponService;
import com.victor.service.MybybookcouponService;
import com.victor.service.PraiseService;
import com.victor.utils.Msg;

@RestController
@RequestMapping("/praise/dianzan")
public class PraiseController {
	@Autowired
	private PraiseService pService;
	@Autowired
	private BybookcouponService bService;
	@Autowired
	private MybybookcouponService mService;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@PostMapping("/getZan")
	public Msg selPraiseByUid(int uid,String time,int pid) {
		Praise praise = new Praise();
		praise.setUid(uid);
		praise.setPid(pid);
		praise.setTime(time);
		if(pService.selPraiseByPid(pid)>0) {
			praise.setFlag(0);
		}else {
			praise.setFlag(1);
		}
		Integer sum = pService.selectPraise(praise);
		 if(sum>=1) {
			 return Msg.fail("重复点赞");
		 }else{
			 pService.insPraise(praise);
				
		 }
		 praise.setPid(0);
		 Integer end = pService.selectPraise(praise);
		 
		 //点赞换购书卷
		 List<Praise> list = pService.selPraiseByFlag(uid);
		 Map<String, Object> map = new HashMap<>();
		 if(list.size()>=3) {
			 for(int i=0; i<3; i++) {
				 int flagq = list.get(i).getFlag();
				 int pidq = list.get(i).getPid();
				 pService.updPraise(uid, pidq);
				 Bybookcoupon bybookcoupon = bService.selBybookcoupon();
				 int bid = bybookcoupon.getId();
				 map.put("bybookcouponid", bid);
				 map.put("flag", 1);
				 map.put("gaintime", sdf.format(new Date()));
				 map.put("userid", uid);
			 }
		 }
		 if(map !=null && !map.isEmpty()) {
			 mService.insMybybookcoupon(map);
		 }
		 return Msg.success();
	}

	@GetMapping("/getSum/{uid}/{time}")
	public Msg getPraiseSum(@PathVariable("uid")int uid,@PathVariable("time")String time) {
		Praise praise = new Praise();
		praise.setUid(uid);
		praise.setTime(time);
		Integer sum = pService.selectPraise(praise);
		return Msg.success().add("sum", sum);
		
	}
}
